package com.zmn.plat.admin.controller.pilot;


import com.google.common.base.Joiner;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto.LayuiTableResponseDTO;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.cas.model.LoginStaff;
import com.zmn.plat.admin.controller.PlatBaseController;
import com.zmn.plat.business.interfaces.pilot.ServCityPriceBService;
import com.zmn.plat.common.constant.OnePriceConsts;
import com.zmn.plat.common.exception.PlatException;
import com.zmn.plat.manager.dictionary.OnePriceDict;
import com.zmn.plat.model.entity.pilot.*;
import com.zmn.plat.services.interfaces.pilot.ChannelPriceCategoryService;
import com.zmn.plat.services.interfaces.pilot.ServCityPriceLogService;
import com.zmn.plat.services.interfaces.pilot.ServCityPriceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 城市试点基础修改Controller
 *
 * @author guoqiao
 * @since 2021-06-25 10:17:20
 */
@Slf4j
@RestController
@RequestMapping("/pilot/city")
public class ServCityPriceModifyController extends PlatBaseController {

    @Resource
    private ServCityPriceService servCityPriceService;

    @Resource
    private ServCityPriceBService bService;

    @Autowired
    private ChannelPriceCategoryService channelPriceCategoryService;
    @Autowired
    protected ServCityPriceLogService logService;

    @RequestMapping(value = "addEdit")
    @ResponseBody
    @RequiresPermissions("/pilot/city/addEdit.action")
    public ResponseDTO addEdit(@RequestBody ServCityPriceAddEditVO vo) {

        LoginStaff mcStaff = getMcStaff();
        vo.setOperatorName(mcStaff.getRealName());
        vo.setOperatorId(mcStaff.getStaffId());
        vo.setStatus(GlobalDict.STATUS_DISABLE);
        List<Integer> ids = bService.addEdit(vo);

        return ids == null ? ResponseDTO.fail("操作失败") : ResponseDTO.success(ids, GlobalConsts.SUCCESS_MSG);
    }

    /**
     * 描述: 修改状态
     *
     * @param ids    id集合
     * @param status 状态
     * @author guoqiao
     * @since 2021-06-25 10:17:20
     */
    @RequestMapping(value = "/updateStatus")
    public ResponseDTO<Boolean> updateStatus(@RequestParam(value = "ids") String ids,
                                             @RequestParam(value = "status") Integer status) {
        if (StringUtil.isBlank(ids)) {
            return ResponseDTO.fail("请选择要更改状态的数据！");
        }
        LoginStaff mcStaff = getMcStaff();
        try {
            List<Integer> list = StringUtil.convertStrsToList(ids);
            // 启动时需要校验是否添加应用分类，未添加这不能启动
            if (status.equals(GlobalDict.STATUS_ENABLE)) {
                if (status.equals(GlobalDict.STATUS_ENABLE)) {
                    checkwhetherOrNotItCanStart(list);
                }
            }

            servCityPriceService.updateStatusBatch(list, status, getMcStaffRealName());
            // 保存日志
            List<ServCityPriceLog> logList = new ArrayList<>();
            list.forEach(x -> {
                ServCityPriceLog log = new ServCityPriceLog();
                log.setCreateTime(DateUtil.getNow());
                log.setRelationId(x);
                log.setContent(String.format("状态变更为:\"%s\"", OnePriceDict.getStatus(status)));
                log.setAbutmenterType((byte) 1);
                log.setAbutmenterId(mcStaff.getStaffId());
                log.setAbutmenter(mcStaff.getStaffName());
                logList.add(log);
            });
            logService.insertBatch(logList);
            return ResponseDTO.success(true, "操作成功！");
        } catch (Exception e) {
            log.error("{},{}", e.getMessage(), e);
            return ResponseDTO.fail(String.format("修改状态失败：%s", e.getMessage()));
        }
    }

    /**
     * 描述: 删除
     *
     * @param relationId 主键
     * @author guoqiao
     * @since 2021-06-25 10:17:20
     */
    @RequestMapping(value = "/delete")
    public ResponseDTO delete(@RequestParam(value = "relationId") Integer relationId) {

        try {
            if (NumberUtil.isNullOrZero(relationId)) {
                return ResponseDTO.fail("请选择要删除的数据！");
            }
            if (!Objects.isNull(servCityPriceService.findById(relationId))) {
                servCityPriceService.deleteByKey(relationId);
                channelPriceCategoryService.deleteByConfigId(relationId, GlobalConsts.YES, GlobalConsts.YES);
            }
            return ResponseDTO.success(true, GlobalConsts.SUCCESS_MSG);

        } catch (Exception e) {
            log.error("删除失败,Exception{},msg{}", e, e.getMessage());
            return ResponseDTO.fail("操作失败！");
        }
    }

    /**
     * 获取日志
     *
     * @param query
     * @return
     */
    @RequestMapping(value = "listCityPriceLog")
    @ResponseBody
    public LayuiTableResponseDTO loadChannelPriceLog(ServCityPriceLogQuery query) {

        List<ServCityPriceLog> logs = logService.listByQuery(query);
        Integer count = logService.countByQuery(query);
        query.setTotalCount(count);
        return LayuiTableResponseDTO.success(query.getTotalCount(), logs);

    }

    /**
     * 判断是否能启动
     *
     * @param list 渠道id
     */
    private void checkwhetherOrNotItCanStart(List<Integer> list) {
        ChannelPriceCategoryQuery categoryQuery = new ChannelPriceCategoryQuery();
        categoryQuery.setConfigIdList(list);
        categoryQuery.setType(OnePriceConsts.CITY_CONFIG);
        List<ChannelPriceCategory> categorys = channelPriceCategoryService.listByQuery(categoryQuery);
        if (CollectionUtils.isEmpty(categorys)) {
            throw new PlatException(String.format("ID【%s】没有关联应用分类，不能启动！", Joiner.on(",").join(list)));
        }
        // 只要有一条没加应该分类就不能启动
        Map<Integer, List<ChannelPriceCategory>> map = categorys.stream()
                .collect(Collectors.groupingBy(ChannelPriceCategory::getConfigId));

        List<Integer> configIds = new ArrayList<>();
        for (Integer index : list) {
            if (CollectionUtils.isEmpty(map.get(index))) {
                configIds.add(index);
            }
        }
        if (!CollectionUtils.isEmpty(configIds)) {
            throw new PlatException(String.format("ID【%s】没有关联应用分类，不能启动！", Joiner.on(",").join(configIds)));
        }
    }

}
